package com.turing.data.scripts.contract.filter

import com.turing.data.engine.TextUtils
import com.turing.data.engine.utils.ScriptsUtils
import com.turing.data.vo.out.review.DependParamsVO
import com.turing.data.vo.out.review.TaskElementVO
import org.apache.commons.lang.SerializationUtils
import org.springframework.util.CollectionUtils
import com.turing.common.util.FileUtils
import com.turing.data.engine.utils.RegexExtract


/**
 * 场景：资产管理合同
 * 版本：Version 1
 * 要素名称：合同规定的主要投资范围及投资组合比例
 */

class ScopeOfInvestment_30176_10_filter {

    static List< TaskElementVO.DrawResultVO > doConvert(DependParamsVO dependParams){

        def REGEX_VALUATION = '投资范围及比例'
        def REGEX_VALUATION_1 = '投资范围如下'
        def REGEX_VALUATION_2 = "．投资范围"
        def REGEX_VALUATION_4 = "投资范围及投资比例"
        def REGEX_VALUATION_NEGATIVE_CASE = "具体投资范围"
        def REGEXES = [REGEX_VALUATION,REGEX_VALUATION_1,REGEX_VALUATION_2,REGEX_VALUATION_4]
        def REGEX_NUMBER = '（1）'
        def REGEX_NUMBER_1 = '（l）'

        List<TaskElementVO.DrawResultVO > trueValueSet = new ArrayList<>()
        List<TaskElementVO.DrawResultVO > resultVOs = ScriptsUtils.tryInitResult(dependParams)
        def relatedObjects = dependParams.relatedModelElements
        def relatedObjectList = null
        if(relatedObjects != null){
            relatedObjectList = relatedObjects.get("标准化")
        }

        if(relatedObjectList != null && relatedObjectList.size()>0){
            for(relatedObject in relatedObjectList){
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(relatedObject.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)
                def start = relatedObject.start
                def end = relatedObject.end
                def expandOffset = 0
                def text = relatedObject.text
                println relatedObjectList.toString()
                boolean findHead = false
                while( expandOffset < 800 && start >  expandOffset  ){
                    def expandString = rawText.substring(start-expandOffset,end)
                    for( REGEX in REGEXES ){
                        if(expandString =~ REGEX){
                            def expandStringExt = rawText.substring(start-expandOffset-80,end)
                            if(expandStringExt =~ REGEX_VALUATION_NEGATIVE_CASE){
                                // break
                            }
                            findHead = true
                            break
                        }
                    }
                    if(findHead){
                        break
                    }
                    expandOffset ++
                }

                if (findHead) {
                    def REGEX_STOP = /.*比例.*%。/
                    def REGEX_STOP_1 = /.*比例.*%\./
                    def REGEX_STOP_2 = /.*比例为.*0%至.*0%/
                    def REGEX_STOP_3 = /.*比例.*%（.*。./
                    def REGEX_STOP_4 = /.*比例.*‰。/
                    def NOT_REGEX_STOP = /.*比例.*%，/
                    def expand = 0
                    while( expand < 250 && rawText.length() > end + expand  ){
                        def expandStr = rawText.substring(end,end+expand)
                        if( ( expandStr =~ REGEX_STOP || expandStr =~ REGEX_STOP_1 || expandStr =~ REGEX_STOP_3 || expandStr =~ REGEX_STOP_4
                                || ( text.length() > 30 && text.substring(text.length()-30) =~ /.*比例.*%。/ ) )
//                                && !(expandStr =~ NOT_REGEX_STOP)
                        ){
                            def startOffset = 0
                            def text0 = rawText.substring( start  - expandOffset , end + expand )
                            def index = text0.indexOf(REGEX_NUMBER)
                            if (index < 0) {
                                index = text0.indexOf(REGEX_NUMBER_1)
                            }
                            if(index > -1){
                                startOffset = index - expandOffset
                            }
                            def JSONTextMap = dependParams.JSONTextMap
                            def fileTextStr = ""
                            fileTextStr = JSONTextMap.get(relatedObject.childTaskSn)
                            TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(relatedObject)
                            objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, expand, fileTextStr, rawText)
                            objectNew.text = rawText.substring( start + startOffset , end + expand )
                            objectNew.businessValue = rawText.substring( start + startOffset, end + expand )
                            trueValueSet.add(objectNew)
                            return trueValueSet
                        }
                        expand ++
                    }
//                }

                }
            }
        }

        if (resultVOs!=null && resultVOs.size()>0) {
            for (int i = 0; i < resultVOs.size(); i++) {
                def drawResultVO = resultVOs.get(i)
                def childTaskSn = drawResultVO.childTaskSn
                if(null == childTaskSn || childTaskSn == ""){
                    continue
                }
                def start = drawResultVO.start
                def end = drawResultVO.end
                def text = drawResultVO.text
                text = text.replaceAll("\n","")
                def textPathMap = dependParams.textPathMap
                def rawPath = textPathMap.get(drawResultVO.childTaskSn)
                def rawText = FileUtils.loadJson(rawPath)

                if( text.contains(REGEX_NUMBER) || text.contains(REGEX_NUMBER_1) ){
                    def expandOffset0 = 0
                    while( expandOffset0 < 850 && start > expandOffset0 ){
                        def expandString = rawText.substring(start-expandOffset0,end)
                        if( expandString =~ REGEX_VALUATION || expandString =~ REGEX_VALUATION_1 || expandString =~ REGEX_VALUATION_2 ){
                            def expandStringExt = rawText.substring(start-expandOffset0-80,end)
                            if(expandStringExt =~ REGEX_VALUATION_NEGATIVE_CASE){
                                break
                            }
                            def index = text.indexOf("（1）")
                            if (index<0) {
                                index = text.indexOf(REGEX_NUMBER_1)
                            }
                            def startOffset = index
                            def endOffset = 0
                            for (int j = 2; j < 1000; j++) {
                                def REGEX = '。（' + j + '）'
                                def expandOffset = 0
                                def replicationEndOffset = endOffset
                                while( expandOffset < 350 && rawText.length() > end + expandOffset + endOffset ){
                                    def expandStr = ""
                                    try {
                                        expandStr = rawText.substring(start+endOffset,end+expandOffset+endOffset)
                                    } catch (Exception e) {
                                        e.printStackTrace()
                                    }
                                    if( expandStr =~ REGEX ){
                                        endOffset += expandOffset
                                        break
                                    }
                                    expandOffset ++
                                }
                                if(replicationEndOffset == endOffset){
                                    break
                                }
                            }

                            def REGEX_STOP = /.*比例.*%。/
                            def REGEX_STOP_1 = /.*比例.*%\./
                            def REGEX_STOP_2 = /.*比例为.*0%至.*0%/
                            def REGEX_STOP_3 = /.*比例.*%（.*。./
                            def REGEX_STOP_4 = /.*比例.*‰。./
                            def NOT_REGEX_STOP = /.*比例.*%，/
                            def expand = 0
                            while( expand < 350 && rawText.length() > end + expand + endOffset ){
                                def expandStr = rawText.substring(end+endOffset,end+expand+endOffset)
                                if( (expandStr =~ REGEX_STOP || expandStr =~ REGEX_STOP_1 || expandStr =~ REGEX_STOP_3 || expandStr =~ REGEX_STOP_4 )  ){
                                    endOffset += expand
                                    break
                                }
                                expand ++
                            }
                            def JSONTextMap = dependParams.JSONTextMap
                            def fileTextStr = ""
                            fileTextStr = JSONTextMap.get(drawResultVO.childTaskSn)
                            TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(drawResultVO)
                            objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText)
                            objectNew.text = rawText.substring( start + startOffset, end + endOffset )
                            objectNew.businessValue = rawText.substring( start + startOffset, end + endOffset )
                            trueValueSet.add(objectNew)
                            return trueValueSet
                        }
                        expandOffset0 ++
                    }
                }
            }
        }

        try{
            if(trueValueSet.size()==0){

                String REGEX0 = /(?<=投资范围及比例|投资范围及投资比例|\(.{1,3}\)投资范围)[^”].+?(资产的比例|资产总值的比例|资产管理计划总资产|资产的\d+%)/
                println dependParams.JSONTextMap.size()
                dependParams.JSONTextMap.forEach(
                        { childTaskSn, jsonText ->
                            RegexExtract.doRuleExtract(REGEX0,childTaskSn, dependParams, jsonText, trueValueSet)
                        }
                )

                if(trueValueSet.size()>0){
                    def textPathMap = dependParams.textPathMap
                    def childTaskSn = trueValueSet[0].childTaskSn
                    def rawPath = textPathMap.get(childTaskSn)
                    def rawText = FileUtils.loadJson(rawPath)
                    def JSONTextMap = dependParams.JSONTextMap
                    def fileTextStr = ""
                    fileTextStr = JSONTextMap.get(childTaskSn)

                    def rawPath0 = textPathMap.get(childTaskSn)
                    def rawText0 = FileUtils.loadJson(rawPath0)
                    def text = trueValueSet[0].text

                    def startOffset = 0
                    def endOffset = 0
                    def keyWord1 = "大额支付行号："
//                    def keyWord2 = "开户行"
                    if(text.contains(keyWord1)){
                        startOffset = text.indexOf(keyWord1) + keyWord1.length()
                        endOffset = 0
                    }
//                    else if(text.contains(keyWord2)){
//                        startOffset = text.indexOf(keyWord2) + keyWord2.length()
//                        endOffset = 0
//                    }

                    TaskElementVO.DrawResultVO objectNew = (TaskElementVO.DrawResultVO) SerializationUtils.clone(trueValueSet[0])
                    objectNew = TextUtils.correctPositionInfoByOffset(objectNew, startOffset, endOffset, fileTextStr, rawText0)
                    trueValueSet.clear()
                    trueValueSet.add(objectNew)
                    return trueValueSet
                }
            }
        }
        catch (Exception e){
            e.printStackTrace()
        }

        if(!CollectionUtils.isEmpty(resultVOs) && resultVOs.size()>0){
            trueValueSet.add(resultVOs[0])
            return trueValueSet
        }

        TaskElementVO.DrawResultVO defaultDrawResultVO = new TaskElementVO.DrawResultVO()
        defaultDrawResultVO.text = ""
        trueValueSet.add(defaultDrawResultVO)
        return  trueValueSet

    }

    static void main(String[] args) {

        def str = "(三）投资范围及比例\n" +
                "资产委托人委托资产管理人实施资产管理的范围为符合国家有关管理部门\n" +
                "规定的资产管理计划可实施投资的金融产品。\n" +
                "本资产管理计划的投资范围及投资比例为:\n" +
                "（1）固定收益类资产:国债、地方政府债、中央银行票据、政策性金融债、\n" +
                "政府支持机构债券、商业性金融债（包括商业银行普通金融债、混合资本债、二\n" +
                "级资本工具等）、公司债（包括一般公司债、可交换债券、可转换债券、私募债\n" +
                "等）、企业债（包括一般企业债、集合企业债）、非金融企业债务融资工具（包\n" +
                "括银行间债券市场发行的企业短期融资券、"
        println str.length()

    }


}
